package com.weijian.controller.admin;

import com.weijian.common.BaseContext;
import com.weijian.common.enums.GlobalErrorCodeConstants;
import com.weijian.common.exception.ServiceException;
import com.weijian.common.pojo.CommonResult;
import com.weijian.dal.dto.UserRegisterDTO;
import com.weijian.dal.entity.User;
import com.weijian.dal.vo.UserVO;
import com.weijian.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public CommonResult<Long> userRegister(@RequestBody UserRegisterDTO UserRegisterDTO) {
        log.info("userRegister:{}", UserRegisterDTO);
        if (UserRegisterDTO == null) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        String userAccount = UserRegisterDTO.getUserAccount();
        String userPassword = UserRegisterDTO.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword);
        return CommonResult.success(result);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public CommonResult<UserVO> userLogin(@RequestBody UserRegisterDTO UserRegisterDTO, HttpServletRequest request) {
        log.info("userLogin:{}", UserRegisterDTO);
        if (UserRegisterDTO == null) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        String userAccount = UserRegisterDTO.getUserAccount();
        String userPassword = UserRegisterDTO.getUserPassword();
        log .info("userPassword:{}", userPassword);
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        UserVO UserVO = userService.userLogin(userAccount, userPassword, request);
        log .info("userLogin:{}", UserVO);
         if (UserVO == null) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }

        return CommonResult.success(UserVO);
    }

    /**
     * 获取当前登录用户
     */
    @GetMapping("/currentUser")
    public CommonResult<User> currentUser() {
        Long userId = BaseContext.getCurrentId();
        return CommonResult.success(User.builder().id(userId).build());
    }

    /**
     * 扣减余额
     */
    @PutMapping("/money/deduct")
    public void deductMoney(@RequestParam("pw") String pw, @RequestParam("amount") Integer amount) {
        userService.deductMoney(pw, amount);
    }
}
